package com.h.files.selector.activity.fragment;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListPopupWindow;
import android.widget.TextView;

import com.h.files.selector.R;
import com.h.files.selector.activity.MultiFileSelectorActivity;
import com.h.files.selector.activity.adapter.NListAdapter;
import com.h.files.selector.activity.listener.OnNScrollListener;
import com.h.files.selector.activity.model.DirctoryModel;
import com.h.files.selector.activity.model.FileModel;
import com.h.files.selector.activity.util.BitmapUtils;
import com.h.files.selector.activity.util.LogUtils;
import com.h.files.selector.activity.util.StringUtils;
import com.h.files.selector.activity.util.UiUtils;
import com.squareup.picasso.Callback;
import com.squareup.picasso.RequestCreator;

@SuppressLint("NewApi")
public class ImageSelectorFragment extends Fragment {

	private Uri cameraUri;
	private MultiFileSelectorActivity activity;
	private List<DirctoryModel> dirctoryList = new ArrayList<DirctoryModel>();
	private int maxNum = 9;
	private boolean isShowCamera = false;
	private ListPopupWindow popup;
	private String[] imgType;

	private GridView gridView;
	private TextView bar;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (200 == msg.what) {
				List<FileModel> data = (List<FileModel>) msg.obj;
				NListAdapter<FileModel> nListAdapter = (NListAdapter<FileModel>) gridView.getAdapter();
				nListAdapter.clear();
				nListAdapter.addData(data);
				nListAdapter.updateUI();
				gridView.smoothScrollToPosition(0);
			}
		}
	};

	private void readerDatabase(final String displayName) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String where = null;
				if (!StringUtils.isNullOrEmpty(displayName)) {
					where = MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " = '" + displayName + "'";
				}
				Cursor cursor = activity.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { "*" }, where, null,
						MediaStore.Images.Media.DATE_ADDED + " desc");
				FileModel file = null;
				List<FileModel> list = null;
				if (300 >= cursor.getCount())
					list = new ArrayList<FileModel>();
				else
					list = new LinkedList<FileModel>();
				if (isShowCamera) {
					file = new FileModel();
					list.add(file);
					file = null;
				}
				if (StringUtils.isNullOrEmpty(displayName)) {
					dirctoryList.clear();
				}
				Map<String, DirctoryModel> fileNum = new HashMap<String, DirctoryModel>();
				while (cursor.moveToNext()) {
					file = new FileModel();
					file.abstractPath = getValue(cursor, MediaStore.Images.Media.DATA);
					file.fileDirctory = new File(file.abstractPath).getParent();
					file.fileName = getValue(cursor, MediaStore.Images.Media.DISPLAY_NAME);
					file.parentName = getValue(cursor, MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
					DirctoryModel dm = null;
					if (!fileNum.containsKey(file.parentName)) {
						dm = new DirctoryModel();
						dm.image = file.abstractPath;
						dm.isSelected = false;
						dm.name = file.parentName;
						dm.path = file.parentName;
						dm.files = 0;
						fileNum.put(file.parentName, dm);
					}
					dm = fileNum.get(file.parentName);
					dm.files += 1;
					fileNum.put(file.parentName, dm);
					file.isSelected = activity.getResultList().contains(file.abstractPath);
					list.add(file);
					file = null;
				}

				if (0 == dirctoryList.size()) {
					DirctoryModel dir = new DirctoryModel();
					dir.files = cursor.getCount();
					dir.image = list.get(isShowCamera ? 1 : 0).abstractPath;
					dir.path = null;
					dir.name = "全部图片";
					dir.isSelected = true;
					dirctoryList.add(dir);
					for (DirctoryModel dm : fileNum.values()) {
						dirctoryList.add(dm);
					}
				}
				cursor.close();
				Message msg = handler.obtainMessage(200, list);
				handler.sendMessage(msg);
			}
		}).start();
	}

	private String getValue(Cursor cursor, String columnName) {
		return cursor.getString(cursor.getColumnIndexOrThrow(columnName));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.f_multi_image_selector, container, false);
		initWidget(view);
		initListener();
		initData();
		return view;
	}

	private void initWidget(View view) {

		imgType = activity.getResources().getStringArray(R.array.imageType);

		gridView = (GridView) view.findViewById(R.id.f_multi_image_gridView);
		bar = (TextView) view.findViewById(R.id.f_multi_image_dir);

		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gridView.setAdapter(new NListAdapter<FileModel>(R.layout.i_image_selector, this.getActivity()) {
			@SuppressLint("ResourceAsColor")
			@Override
			public void bindData(int position, View convertView, ViewGroup parent, final FileModel t) {
				ImageView imageView = (ImageView) getView(R.id.i_file_type);
				int columnWidth = gridView.getColumnWidth();
				convertView.setLayoutParams(new GridView.LayoutParams(columnWidth, columnWidth));
				convertView.setBackgroundColor(android.R.color.holo_red_light);
				RequestCreator rc = null;
				if (0 == position && isShowCamera)
					rc = BitmapUtils.getPicasso().load(R.drawable.asy);
				else {
					if (!t.isLoadFail) {
						rc = BitmapUtils.getPicasso().load(new File(t.abstractPath)).error(R.drawable.default_image);
					} else {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_image);
					}
				}
				rc.placeholder(R.drawable.default_image).resize(columnWidth, columnWidth).centerCrop().config(Config.ARGB_8888).into(imageView, new Callback() {
					@Override
					public void onError() {
						t.isLoadFail = true;
					}

					@Override
					public void onSuccess() {
					}
				});
				getView(R.id.i_file_selected).setVisibility(t.isSelected ? View.VISIBLE : View.GONE);
			}
		});

	}

	private void initListener() {
		gridView.setOnScrollListener(new OnNScrollListener(gridView));
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				NListAdapter<FileModel> adapter = (NListAdapter<FileModel>) gridView.getAdapter();
				FileModel fileModel = adapter.getItem(position);
				if (0 == position && isShowCamera) {
					if (activity.getResultList().size() >= maxNum) {
						UiUtils.showLong(activity, "已达到最大数量...");
						return;
					}
					// 判断是否挂载了SD卡
					String savePath = "";
					String storageState = Environment.getExternalStorageState();
					if (storageState.equals(Environment.MEDIA_MOUNTED)) {

						savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/multiFileSelector/Camera/";
						File savedir = new File(savePath);
						if (!savedir.exists()) {
							savedir.mkdirs();

						}
					}
					// 没有挂载SD卡，无法保存文件
					if (StringUtils.isNullOrEmpty(savePath)) {
						UiUtils.showShort(activity, "无法保存照片，请检查SD卡是否挂载");
						return;
					}

					String fileName = "camera_" + StringUtils.getDateTimeNow("yyyyMMddHHmmss") + ".jpg";// 照片命名
					File out = new File(savePath, fileName);
					if (!out.exists()) {
						try {
							out.createNewFile();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					cameraUri = Uri.fromFile(out);
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
					startActivityForResult(intent, 10001);
				} else {
					if (!activity.getResultList().contains(fileModel.abstractPath)) {
						if (activity.getResultList().size() >= maxNum) {
							UiUtils.showLong(activity, "已达到最大数量...");
							return;
						}
						fileModel.isSelected = true;
						activity.getResultList().add(fileModel.abstractPath);
					} else {
						fileModel.isSelected = false;
						activity.getResultList().remove(fileModel.abstractPath);
					}
					adapter.updateUI();
					activity.setSelectedNum(activity.getResultList().size());
				}
			}
		});
		bar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (null != popup && popup.isShowing()) {
					popup.dismiss();
					popup = null;
				} else {
					popup = new ListPopupWindow(activity);
					popup.setModal(true);
					popup.setAnchorView(v);
					popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
					popup.setAdapter(new NListAdapter<DirctoryModel>(R.layout.i_dirctory, activity, dirctoryList) {
						@Override
						public void bindData(int position, View convertView, ViewGroup parent, DirctoryModel t) {
							ImageView iv = (ImageView) getView(R.id.i_folder);
							BitmapUtils.getPicasso().load(new File(t.image)).placeholder(R.drawable.default_image).resize(80, 80).centerCrop().into(iv);
							setText(R.id.i_dirctory_name, t.name);
							setText(R.id.i_dirctory_list, "共" + t.files + "张图片");
							getView(R.id.i_dirctory_selected).setVisibility(t.isSelected ? View.VISIBLE : View.GONE);
						}
					});
					popup.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
							NListAdapter<DirctoryModel> adapter = ((NListAdapter<DirctoryModel>) parent.getAdapter());
							int end = adapter.getCount();
							DirctoryModel selectedItem = null;
							for (int i = 0; i < end; i++) {
								DirctoryModel dm = adapter.getItem(i);
								dm.isSelected = position == i;
								if (position == i)
									selectedItem = dm;
							}
							bar.setText(selectedItem.name);
							popup.getListView().setSelection(position);
							readerDatabase(selectedItem.path);
							popup.dismiss();
						}
					});
					popup.setWidth(UiUtils.getScreenWidth(activity));
					popup.setHeight((UiUtils.getScreenHeight(activity) / 11) * 5);
					popup.show();
				}
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogUtils.e(cameraUri.getPath());
		if (resultCode == Activity.RESULT_OK) {
			if (10001 == requestCode) {
				activity.getResultList().add(cameraUri.getPath());
				activity.setNewResult(Activity.RESULT_OK);
			}
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = (MultiFileSelectorActivity) activity;
		this.maxNum = this.activity.getIntent_request_key_max_num();
		this.isShowCamera = this.activity.isIntent_request_key_showCamera();
	}

	private void initData() {
		readerDatabase(null);
	}
}
